package com.exam.service.serviceImpl;

import com.exam.dataobject.Examination;
import com.exam.dataobject.mapper.ExaminationMapper;
import com.exam.repository.ExaminationRepository;
import com.exam.service.ExaminationContentService;
import com.exam.service.ExaminationService;
import com.exam.utils.paramAccpet.ExaminationInfo;
import com.exam.vo.ExaminationVO;
import com.exam.vo.QuestionVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by v
 * Date:2019/1/16
 * Time:15:39
 */
@Service
public class ExaminationServiceImpl implements ExaminationService {

    @Autowired
    private ExaminationRepository examinationRepository;

    @Autowired
    private ExaminationContentService examinationContentService;

    @Autowired
    private ExaminationMapper examinationMapper;

    @Override
    public void designExamination(ExaminationInfo examinationInfo) {

        Examination examination = new Examination();
        examination.setTitle(examinationInfo.getTitle());
        examinationRepository.save(examination);
        examinationContentService.setExaminationContent(examination.getExaminationId(), examinationInfo.getQuestionId());

        examination.setTotalScore(this.getTotalScore(examination.getExaminationId()));
        examinationRepository.save(examination);
    }

    @Override
    public Integer getTotalScore(Integer examinationId) {

        List<Integer> questionScore = examinationMapper.findQuestionScore(examinationId);
        Integer totalScore = 0;
        for (Integer i : questionScore)
            totalScore += i;

        return totalScore;
    }

    @Override
    public ExaminationVO getExamination(Integer examinationId) {

        Examination examination = examinationRepository.findByExaminationId(examinationId);
        ExaminationVO examinationVO = new ExaminationVO();

        List<QuestionVO> questionVOList = examinationMapper.getQuestionList(examinationId);

        examinationVO.setTitle(examination.getTitle());
        examinationVO.setTotalScore(examination.getTotalScore());
        examinationVO.setQuestionVOList(questionVOList);

        return examinationVO;
    }

    @Override
    public PageInfo<Map<String, Object>> getExaminationList(Integer page, Integer size) {

        PageHelper.startPage(page, size);
        Page<Map<String, Object>> all = examinationMapper.getExaminationList();
        return all.toPageInfo();
    }
}
